package com.zhang.crm.handler;

import com.zhang.crm.result.CodeEnum;
import com.zhang.crm.result.R;
import com.zhang.crm.util.JSONUtil;
import com.zhang.crm.util.ResponseUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ZhangAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //访问失败，返回json
        R r = R.FAIL(CodeEnum.LOGIN_FAIL_ILLEGALITY, accessDeniedException.getLocalizedMessage());
        //返回json
        String json = JSONUtil.toJSON(r);
        accessDeniedException.printStackTrace();
        System.out.println(accessDeniedException.getMessage());

        //写入前端页面
        ResponseUtil.write(response,json);
    }
}
